﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using System.Linq.Dynamic.Core;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using HZYProject.Data;

namespace HZYProject.Service
{
    public class RoleService : IRoleService
    {

        private readonly IRepository<Role, Guid> _roleRepository;
        private readonly HZYProjectDbContext _dbContext;
        public RoleService(IRepository<Role, Guid> roleRepository,
             HZYProjectDbContext dbContext
            )
        {
            _dbContext = dbContext;
            _roleRepository = roleRepository;

        }

        public void FenPeiModule(Guid roleId, Guid[] moduels)
        {
            var role = _dbContext.Roles.Where(x => x.RoleID == roleId).Include("Modules").FirstOrDefault();
            role.Modules.Clear();
            foreach (var item in moduels)
            {
                role.Modules.Add(_dbContext.Modules.FirstOrDefault(x=>x.ModuleID==item));
            }
            _dbContext.SaveChanges();
        }

        public async Task<PagedResultDto<Role>> GetPaginatedResult(GetRoleInput input)
        {
            var query = _roleRepository.GetAll();
            //搜索
            if (!string.IsNullOrEmpty(input.RoleName))
            {
                query = query.Where(x => x.Name.Contains(input.RoleName));
            }
            if (!string.IsNullOrEmpty(input.Key))
            {
                query = query.Where(x => x.Keys.Contains(input.Key));
            }


            //统计查询数据的总条数，用于分页计算总页数
            var count = query.Count();
            //根据需求进行排序，然后进行分页逻辑的计算
            query = query.OrderByDescending(x => x.RoleID).Skip((input.CurrentPage - 1) * input.MaxResultCount).Take(input.MaxResultCount);
            //将查询结果转换为List集合，加载到内存中
            var models = await query.AsNoTracking().ToListAsync();


            var dtos = new PagedResultDto<Role>
            {
                TotalCount = count,
                CurrentPage = input.CurrentPage,
                MaxResultCount = input.MaxResultCount,
                Data = models,
                FilterText = input.FilterText,
            };
            return dtos;
        }


        public Role GetRole(Guid roleId)
        {
            return _roleRepository.GetAll().Include("Modules").FirstOrDefault(x => x.RoleID == roleId);
        }
    }
}
